<template>
    <div class="login w-full h-[100vh] bg-login-bg bg-fixed bg-cover flex items-center justify-center p-4">
        <div class="mask w-full sm:w-[80%] md:w-[60%] lg:w-[40%] bg-[rgba(255,255,255,.5)] rounded-custom truncate p-4">
            <div class="title h-[3.75rem] text-center flex items-center justify-center text-[1.5625rem] text-primary">
                你我正少年 心底事无人知 唯彼此心照不宣 共此念
            </div>
            <div class="login w-full sm:w-[80%] md:w-[60%] lg:w-[60%] mx-auto">
                <n-form ref="formRef" :model="forgetForm" :rules="rules" label-placement="left" label-width="auto">
                    <n-form-item path="email" label="邮箱">
                        <n-input v-model:value="forgetForm.email" size="large" round placeholder="请输入您的邮箱">
                            <template #prefix>
                                <img :src="email" alt="SVG Image" width="" height="" />
                            </template>
                        </n-input>
                    </n-form-item>
                    <n-form-item path="password" label="新密码">
                        <n-input v-model:value="forgetForm.password" size="large" round type="password"
                            placeholder="请输入新密码" show-count show-password-on="click" :maxlength="16">
                            <template #prefix>
                                <img :src="pwd" alt="SVG Image" width="" height="" />
                            </template>
                        </n-input>
                    </n-form-item>
                    <n-form-item path="confirmPassword" label="确认密码">
                        <n-input v-model:value="confirmPassword" size="large" round type="password"
                            placeholder="请再次输入新密码" show-count show-password-on="click" :maxlength="16">
                            <template #prefix>
                                <img :src="pwd" alt="SVG Image" width="" height="" />
                            </template>
                        </n-input>
                    </n-form-item>
                    <n-form-item path="code" label="验证码">
                        <n-input v-model:value="forgetForm.code" size="large" round placeholder="请输入验证码">
                            <template #prefix>
                                <img :src="yzm" alt="SVG Image" width="" height="" />
                            </template>
                        </n-input>
                        <n-button @click="getVerificationCode" :disabled="isButtonDisabled">{{ buttonText }}</n-button>
                    </n-form-item>
                    <div
                        class="btn w-[35%] flex flex-col items-center justify-center mx-[auto] mt-[0.625rem] mb-[0.625rem]">
                        <n-button type="info" @click="sub" class="mx-[auto]">提交</n-button>
                    </div>

                </n-form>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useMessage } from 'naive-ui';
import email from '@/assets/icon/email.svg';
import pwd from '@/assets/icon/pwd.svg';
import yzm from '@/assets/icon/yzm.svg';
import { reqForgetPwd, reqResetPwd } from '@/api/login';
import { AsyncTaskHandler } from '@/utils/asyncTaskHandler';
import { type FormItemRule, type FormRules, type FormInst } from 'naive-ui'
import { useRouter } from 'vue-router';
const formRef = ref<FormInst | null>(null)
const message = useMessage();
const router = useRouter();
const isButtonDisabled = ref(false);
const buttonText = ref('获取验证码');
const confirmPassword = ref("")
const forgetForm = reactive({
    email: '',
    code: '',
    password: '',
});

const validateEmail = (rule: FormItemRule,
    value: string,
    callBack: any) => {
    if (!value) {
        return new Error('请输入邮箱地址');
    }
    const emailPattern = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
    if (!emailPattern.test(value)) {
        return new Error('请输入有效的邮箱地址');
    }
    return callBack();
};

const validateVerificationCode = (rule: FormItemRule,
    value: string,
    callBack: any) => {
    if (!value) {
        return new Error('请输入验证码');
    }
    return callBack();
};

const validatePassword = (rule: FormItemRule,
    value: string,
    callBack: any) => {
    if (!value) {
        return new Error('请输入新密码');
    }
    return callBack();
};

const validateConfirmPassword = (rule: FormItemRule,
    value: string,
    callBack: any) => {
    if (!confirmPassword.value) {
        return new Error('请再次输入新密码');
    }
    if (confirmPassword.value !== forgetForm.password) {
        return new Error('两次输入密码不同');
    }
    return callBack();
};

const rules = {
    email: [
        { key: 'email', required: true, validator: validateEmail, trigger: 'blur' }
    ],
    code: [
        { required: true, validator: validateVerificationCode, trigger: 'blur' }
    ],
    password: [
        { required: true, validator: validatePassword, trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, validator: validateConfirmPassword, trigger: 'blur' }
    ]
};

const handleSubmit = async () => {
    if (formRef.value) {
        //@ts-ignore
        const res = await AsyncTaskHandler.handleSingleTask(reqForgetPwd({ email: forgetForm.email }));
        if (res.code === 0) {
            message.success("重置密码的链接已发送到您的邮箱，请查收。");
        } else {
            message.error("发送重置密码链接失败，请重试。");
        }
    }
};
const getVerificationCode = () => {
    if (formRef.value) {
        formRef.value.validate(async (valid) => {
            if (!valid) {
                isButtonDisabled.value = true;
                buttonText.value = '60s后重新获取';
                let countdown = 60;
                const timer = setInterval(() => {
                    countdown--;
                    buttonText.value = `${countdown}s后重新获取`;
                    if (countdown === 0) {
                        clearInterval(timer);
                        isButtonDisabled.value = false;
                        buttonText.value = '获取验证码';
                    }
                }, 1000);
                handleSubmit()
            }
        }, (rule: any) => {
            return rule?.key === 'email'
        });
    }

};
// 重置密码
const sub = () => {     
    if (formRef.value) {
        formRef.value.validate(async (vali: any) => {
            if (!vali) {
                let res = await AsyncTaskHandler.handleSingleTask(reqResetPwd(forgetForm));
                if (res.code === 0) {
                    message.success(res.data);
                    router.replace('/login');
                } else {
                    message.error(res.msg);
                }
            }
        });
    }
}

</script>

<style scoped></style>